
import { Toast, MessageBox } from "mint-ui";

function err_400(_this) {
    Toast({
        message: "登录失败,请重新登录",
        position: "middle",
        duration: 2000
    });
    localStorage.removeItem("autoremember");
    if (_this.$route.path != "/LoginPage/Login") {
        _this.$router.push({
            path: "/LoginPage",
            query: { redirect: _this.$route.fullPath }
        });
    }
}

function err_401(_this) {
    Toast({
        message: "登录失效,请重新登录",
        position: "middle",
        duration: 2000
    });
    if (_this.$route.path != "/LoginPage/Login") {
        _this.$router.push({
            path: "/LoginPage",
            query: { redirect: _this.$route.fullPath }
        });
    }
}

function err_403(_this) {
    MessageBox.confirm("登录已过期,是否重新登录?").then(
        action => {
            var autoremember = localStorage.getItem("autoremember");
            if (autoremember == null) {
                sessionStorage.removeItem("cubelibrarytoken");
                if (_this.$route.path != "/LoginPage/Login") {
                    _this.$router.push({
                        path: "/LoginPage",
                        query: { redirect: _this.$route.fullPath }
                    });
                }
            } else {
                _this.$http.post("checkAutoLoginInfo", { token: autoremember }).then(response => {
                    sessionStorage.setItem("cubelibrarytoken", response.body);
                    _this.$router.push({
                        path: _this.$route.query.redirect ? _this.$route.query.redirect : "/",
                    });
                });
            }
        },
        cancel => {
            sessionStorage.removeItem("cubelibrarytoken");
            localStorage.removeItem("autoremember");
            if (_this.$route.path != "/LoginPage/Login") {
                _this.$router.push({
                    path: "/LoginPage",
                    query: { redirect: _this.$route.fullPath }
                });
            }
        }
    );
}

function err_404_500(_this) {
    Toast({
        message: "服务器开小差啦，请稍候再试",
        position: "middle",
        duration: 2000
    });
}

function error(status, _this) {
    console.log("=========> " + status + " <=========");

    if (status == 401) {
        err_401(_this)
    }

    if (status == 400) {
        err_400(_this);
    }
    if (status == 403) {
        err_403(_this);
    }

    if (status == 404 || status == 500) {
        err_404_500(_this);
    }
}

export default error;